package com.lonwin.mes2u8.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lonwin.mes2u8.common.MesConfig;
import com.lonwin.mes2u8.domain.mes.MesBatchCodeInfo;
import com.lonwin.mes2u8.domain.mes.MesCommonResult;
import com.lonwin.mes2u8.util.MyHttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author DELL
 * @Date 2023-12-26 17:32
 */
@Service
@Slf4j
public class BatchCodeService {

    @Resource
    private MesConfig mesConfig;
    @Resource
    private MesTokenService mesTokenService;


//    public List<MesBatchCodeInfo> queryMesBatchList(LocalDateTime start, LocalDateTime end) {
//
//        Map<String, String> batchCodeParam = Maps.newHashMap();
//        batchCodeParam.put("createTime_start", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(start));
//        batchCodeParam.put("createTime_end", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(end));
//
     public List<MesBatchCodeInfo> queryMesBatchList() {
         Map<String, String> batchCodeParam = Maps.newHashMap();
        String batchCodeResult = MyHttpClientUtil.sendPostRequest(
                mesConfig.getAddress() + mesConfig.getBatchCodeUrl(),
                mesTokenService.buildTokenHeader(),
                JSONObject.toJSONString(batchCodeParam),
                MyHttpClientUtil::handleJsonResponse
        );

        MesCommonResult<List<MesBatchCodeInfo>> batchCodeInfoResult = JSONObject.parseObject(batchCodeResult, new TypeReference<MesCommonResult<List<MesBatchCodeInfo>>>() {}.getType());

        if (Objects.isNull(batchCodeInfoResult) || !batchCodeInfoResult.isSuccess()) {
            log.error("BatchCodeService.queryMesBatchList occur exception by mes return failed : {}", Objects.isNull(batchCodeInfoResult) ? "null" : batchCodeInfoResult.toString());
            throw new RuntimeException("BatchCodeService.queryMesBatchList return failed");
        }

        List<MesBatchCodeInfo> result = batchCodeInfoResult.getResult();
        if (result == null || result.isEmpty()) {
            return Lists.newArrayList();
        }

        List<MesBatchCodeInfo> mesBatchCodeInfoList = Lists.newArrayList();
        for (Object res : result) {
            MesBatchCodeInfo mesBatchCodeInfo = JSONObject.parseObject(JSONObject.toJSONString(res), MesBatchCodeInfo.class);
            if (mesBatchCodeInfo != null) {
                mesBatchCodeInfoList.add(mesBatchCodeInfo);
            }
        }

        return mesBatchCodeInfoList;
    }
}
